﻿$.fn.exists = function () {
    return $(this).length != 0;
}
$.preview = function (obj, downloadUrl) {
    var temp = obj.attr("fileTempName");
    var file = obj.text();
    var data = { fileName: decodeURI(file), fileTempName: temp }
    $.download(downloadUrl, data);
}

/*************************************
URL ENCODE / DECODE
**************************************/
$.extend({ URLEncode: function (c) {
    var o = ""; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != "") {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == " ") o += "+"; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += "%" + (h.length < 2 ? "0" : "") + h.toUpperCase();
            } x++;
        }
    } return o;
},
    URLDecode: function (s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != "") {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});


$.fn.upload = function (options) {
    var waitDialog = null;

    options = $.extend({}, {
        uploadUrl: "",
        downloadUrl: null,
        downloadTempUrl: null,
        removeUrl: null,
        multiple: true,
        maxFileSize: 4 * 1024000, // 4MB
        attachments: [],
        onSuccess: function (file) { },
        onComplete: function (e) { }
    }, options);

    var id = $(this).attr("id");

    // file attachments
    var content = "" +
      "<div class=\"t-widget t-upload\">" +
      "   <div class=\"t-button t-upload-button\">" +
      "      <span>Upload</span>" +
      "      <input type=\"file\" id=\"" + id + "\" name=\"" + id + "\" autocomplete=\"off\">" +
      "   </div>";

    if (options.attachments.length > 0) {
        content += "<ul class=\"t-upload-files\">";
        $.each(options.attachments, function (index, attachment) {
            content +="<li class=\"t-file\">"
            content += "<span class=\"t-filename\" title=\"" + attachment.fileName + "\"><a href=\"#\" fileTempName=\"" + attachment.fileTempName + "\">" + attachment.fileName + "</a></span>"          
            content +="</li>"
        });
        content += "</ul>";

    }

    content += "</div>";

    $(this).replaceWith(content);


    // init upload
    $("#" + id).tUpload({
        async: {
            saveUrl: options.uploadUrl,
            removeUrl: options.removeUrl,
            autoUpload: true
        },
        multiple: options.multiple,
        onLoad: function (e) {

        },
        onSelect: function (e) {
            var result = true;
            if (options.multiple == false) {
                if ($("#" + id).parent().parent().find("a[fileTempName]").exists()) {
                    $("#" + id).parent().parent().find(".t-file").remove();
                }
            }

            $.each(e.files, function (index, file) {
                if (file.size > options.maxFileSize) {
                    result = false;
                    return result;
                }
            });

            if (!result) {
                e.preventDefault();
                return false;
            }
        },

        onSuccess: function (e) {
            files = eval("(" + e.XMLHttpRequest.responseText + ")");
            if (typeof file == "string") {

            } else {
                var tFileName = $(".t-upload-files .t-file .t-filename").filter(function () { return $(this).attr("title") == files.FileName });
                tFileName.attr("title", "");
                tFileName.html("<a href=\"#\" fileTempName=\"" + files.FileTempName + "\">" + files.FileName + "</a>");
                $("a", tFileName).click(function () {
                    $.preview($(this), options.downloadUrl);
                    return false;
                });
                options.onSuccess(files);
            }
        },
        onError: function (e) {

        },
        onComplete: function (e) {
            $(".t-upload-files .t-file a[fileTempName]").each(function () {
                var parent = $(this).parents(".t-file");
                if (!$(".t-delete", parent).exists()) {
                    parent.append("<button class=\"t-button t-button-icontext t-upload-action\" type=\"button\"><span class=\"t-icon t-delete\"></span>Remove</button>");
                    $(".t-button", parent).click(function () {
                        $(this).parents(".t-file").remove();
                        if (!$(".t-upload-files .t-file").exists()) {
                            $(".t-upload-files").remove();
                        }
                    });
                }
            });
            options.onComplete(e);

        },
        onCancel: function (e) { },
        onRemove: function (e) { }
    });

    return {
        getFiles: function () {
            var attachments = [];
            $("ul.t-upload-files a[fileTempName]").each(function () {
                var parent = $(this).parents(".t-file");
                attachments.push({
                    fileName: $(this).text(),
                    fileTempName: $(this).attr("fileTempName"),
                    edit: $(".t-delete", parent).exists()
                });
            });
            return attachments;
        }
    }

}